package com.tzy.note.base.redis.lock;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LockController {
//    @Autowired
//    private Redisson

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 减库存,高并发下的问题
     *      解决方案：单体应用加 synchronized块
     *
     * @return
     */
    @RequestMapping("/deduct_stock")
    public String deductStock(){
        synchronized (this) {
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));//jedis.get("stock")
            if (stock > 0) {
                int realStock = stock - 1;
                stringRedisTemplate.opsForValue().set("stock", realStock + ""); //jedis.set(key,value)
                System.out.println("扣减成功，剩余库存" + realStock);
            } else {
                System.out.println("扣减众失败，库存不足");
            }
            return "end";
        }
    }
}
